<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1">
    <meta name="referrer" content="never">
    <title>默认参数函数</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul {
            list-style: none;
        }
    </style>
</head>
<body>
    
    <script type="text/javascript">
        /* 
        默认参数
            1. 简单类型值的默认参数
                使用三元运算式
                短路语句
            2. 引用类型值的默认参数
                使用 对象合并的方法 Object.assign(默认参, 实参)
        */

        function sum(a, b){
            // if(a === undefined){
            //     a = 0;
            // }
            // if(b === undefined){
            //     b = 0;
            // }
            a = a ? a : 0;
            b = b || 0;
            return a + b;
        }

        console.log(sum()); // 0
        console.log(sum(1)); // 1
        console.log(sum(1,3)); // 4 


        function sayName(obj){
            obj = Object.assign({
                name: "李白"
            }, obj);

            console.log(obj.name);
        }

        sayName(); // "李白"
        sayName({}); // "李白"
        sayName({ name: "张安" }); // "张安"

        console.clear();
        // ES6 函数简写默认参写法： function(形参 = 默认参){}
        function add(a = 0, b = 0){
            console.log(a + b);
        }
        add(); // 0;
        add(1); // 1;
        add(undefined, 4); // 4;
        add(4,5); // 9

        function saidName(obj){
            obj = Object.assign({
                name: "李白"
            }, obj);

            console.log(obj.name);
        }

        saidName(); // "李白"
        saidName({}); // "李白"
        saidName({ name: "张安" }); // "张安"
    </script>
</body>
</html>